package com.example.bledemo.ui;

import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;

import com.example.bledemo.R;
import com.example.bledemo.util.IpSettingsManager;
import com.example.bledemo.util.NetworkUtils;

/**
 * IP设置功能测试Activity
 */
public class TestIpSettingsActivity extends BaseActivity {

    private TextView tvResult;
    private Button btnTestConnection;
    private Button btnLoadSettings;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_test_ip_settings;
    }

    @Override
    protected void initViews() {
        tvResult = findViewById(R.id.tv_result);
        btnTestConnection = findViewById(R.id.btn_test_connection);
        btnLoadSettings = findViewById(R.id.btn_load_settings);
        
        btnTestConnection.setOnClickListener(v -> testConnection());
        btnLoadSettings.setOnClickListener(v -> loadSettings());
    }

    @Override
    protected void initData() {
        loadSettings();
    }

    private void testConnection() {
        String ipAddress = IpSettingsManager.getIpAddress(this);
        int port = IpSettingsManager.getPort(this);
        
        if (ipAddress.isEmpty() || port == 0) {
            showToast("请先设置IP地址和端口");
            return;
        }
        
        tvResult.setText("正在测试连接...");
        
        // 在后台线程中测试连接
        new Thread(() -> {
            NetworkUtils.ConnectionResult result = NetworkUtils.testTcpConnection(ipAddress, port);
            
            runOnUiThread(() -> {
                if (result.isSuccess()) {
                    tvResult.setText("连接成功！\nIP: " + ipAddress + "\n端口: " + port);
                } else {
                    tvResult.setText("连接失败：\n" + result.getMessage() + "\nIP: " + ipAddress + "\n端口: " + port);
                }
            });
        }).start();
    }

    private void loadSettings() {
        String ipAddress = IpSettingsManager.getIpAddress(this);
        int port = IpSettingsManager.getPort(this);
        
        if (ipAddress.isEmpty() && port == 0) {
            tvResult.setText("未找到保存的设置");
        } else {
            tvResult.setText("已保存的设置：\nIP: " + ipAddress + "\n端口: " + port);
        }
    }
} 